<template>
  <div class="modal-overlay" @click.self="closeModal">
    <div class="modal-container">
      <button class="close-btn" @click="closeModal">
        <XIcon class="icon" />
      </button>

      <div v-if="isLoading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <template v-else>
        <div v-if="note" class="note-content">
          <!-- 用户信息 -->
          <div class="user-info">
            <img
              :src="note?.user?.avatar ?? 'https://picsum.photos/id/64/100/100'"
              alt="用户头像"
              class="avatar"
              @error="handleAvatarError"
            >
            <div class="user-details">
              <div class="username">{{ note?.user?.name ?? '匿名用户' }}</div>
              <div class="post-time">{{ formatDate(note?.createdAt) }}</div>
            </div>
            <button
              v-if="!isCurrentUser && authStore.isAuthenticated"
              class="follow-btn"
              @click="handleFollow"
              :disabled="isFollowingLoading"
            >
              {{ isFollowing ? '已关注' : '关注' }}
            </button>
          </div>

          <!-- 封面图片 -->
          <img
            v-if="note?.coverImage"
            :src="note.coverImage"
            alt="笔记封面"
            class="cover-image"
            @error="handleCoverImageError"
          >

          <!-- 笔记内容 -->
          <h2 class="note-title">{{ note?.title ?? '无标题' }}</h2>
          <div class="note-text" v-html="note?.content ?? ''"></div>

          <!-- 互动按钮 -->
          <div class="action-buttons">
            <button
              class="action-btn"
              :class="{ active: note?.isLiked }"
              @click="handleLike(note.id)"
              :disabled="isLiking"
            >
              <HeartIcon class="btn-icon" :fill="note?.isLiked ? 'currentColor' : 'none'" />
              <span>{{ note?.likes ?? 0 }}</span>
            </button>

            <button class="action-btn" @click="focusCommentInput">
              <MessageCircleIcon class="btn-icon" />
              <span>{{ commentCount }}</span>
            </button>

            <button
              class="action-btn"
              :class="{ active: note?.isCollected }"
              @click="handleCollect(note.id)"
              :disabled="isCollecting"
            >
              <BookmarkIcon class="btn-icon" :fill="note?.isCollected ? 'currentColor' : 'none'" />
              <span>{{ note?.collects ?? 0 }}</span>
            </button>
          </div>

          <!-- 评论列表 -->
          <div class="comments-section">
            <h3 class="section-title">评论 ({{ commentCount }})</h3>

            <div v-if="commentsLoading" class="loading-comments">
              <div class="small-spinner"></div>
            </div>

            <div v-else-if="safeComments.length === 0" class="no-comments">暂无评论</div>

            <div v-else class="comments-list">
              <div
                v-for="comment in safeComments"
                :key="comment.id"
                class="comment-item"
              >
                <img
                  :src="comment?.avatarUrl ?? 'https://picsum.photos/id/64/40/40'"
                  alt="用户头像"
                  class="comment-avatar"
                  @error="handleCommentAvatarError"
                >
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-user">{{ comment?.nickname ?? '匿名用户' }}</span>
                    <span class="comment-time">{{ formatDate(comment?.createdAt) }}</span>
                  </div>
                  <p class="comment-text">{{ comment?.content ?? '' }}</p>

                  <!-- 回复按钮 -->
                  <button class="reply-btn" @click="startReply(comment.id, comment.nickname)">
                    回复
                  </button>

                  <!-- 显示回复 -->
                  <div v-if="comment.replies?.length" class="replies">
                    <div
                      v-for="reply in comment.replies"
                      :key="reply.id"
                      class="reply-item"
                    >
                      <img
                        :src="reply?.avatarUrl ?? 'https://picsum.photos/id/64/40/40'"
                        alt="用户头像"
                        class="reply-avatar"
                        @error="handleCommentAvatarError"
                      >
                      <div class="reply-content">
                        <div class="reply-header">
                          <span class="reply-user">{{ reply?.nickname ?? '匿名用户' }}</span>
                          <span class="reply-time">{{ formatDate(reply?.createdAt) }}</span>
                        </div>
                        <p class="reply-text">{{ reply?.content ?? '' }}</p>

                        <!-- 回复按钮 -->
                        <button class="reply-btn" @click="startReply(reply.id, reply.nickname)">
                          回复
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 评论输入框 -->
          <div class="comment-input-container">
            <div v-if="replyingTo" class="replying-to">
              正在回复 @{{ replyingToUsername }}
              <button class="cancel-reply" @click="cancelReply">取消</button>
            </div>

            <input
              type="text"
              :placeholder="replyingTo ? '写回复...' : '写评论...'"
              class="comment-input"
              v-model="commentText"
              ref="commentInput"
              @keyup.enter="submitComment"
            >
            <button
              class="send-btn"
              @click="submitComment"
              :disabled="isCommenting || !commentText.trim()"
            >
              发送
            </button>
          </div>
        </div>

        <div v-else class="error-state">
          <p>无法加载笔记详情</p>
          <p v-if="error" class="error-message">{{ error }}</p>
          <button class="retry-btn" @click="fetchNote">重试</button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { 
  XIcon, 
  HeartIcon, 
  BookmarkIcon,
  MessageCircleIcon
} from 'lucide-vue-next'
import { useNoteStore } from '@/store/notes'
import { useAuthStore } from '@/store/auth'
import { useFollowStore } from '@/store/follows'
import { useCommentStore } from '@/store/comments'
import { formatDate } from '@/utils/date'
import { useLikeStore } from '@/store/likes'
import { useCollectionStore } from '@/store/collections'




const props = defineProps({
  noteId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['close'])

// 存储
const noteStore = useNoteStore()
const authStore = useAuthStore()
const followStore = useFollowStore()
const commentStore = useCommentStore()

// 状态
const { currentNote, isLoading, error } = storeToRefs(noteStore)
const { comments, isLoading: commentsLoading } = storeToRefs(commentStore)
const isFollowing = ref(false)
const isFollowingLoading = ref(false)
const commentText = ref('')
const isCommenting = ref(false)
const commentInput = ref(null)
const isLiking = ref(false)
const isCollecting = ref(false)
const replyingTo = ref(null) // 存储正在回复的评论ID
const replyingToUsername = ref('') // 存储正在回复的用户名

// 计算属性
const note = computed(() => currentNote.value)



const isCurrentUser = computed(() => {
  return authStore.user && note.value?.user && authStore.user.id === note.value.user.id
})
const safeComments = computed(() => comments.value || []) // 安全评论列表

// 使用全局评论数
const commentCount = computed(() => {
  return commentStore.getCommentCountByNoteId(note.value.id) || 0
})

// 方法
const fetchNote = async () => {
  try {
    await noteStore.fetchNoteById(props.noteId)

    const rawNote = currentNote.value
    if (!rawNote) return

    const likeStore = useLikeStore()
    const collectStore = useCollectionStore()

    const [likeCount, collectCount] = await Promise.all([
      likeStore.fetchLikeCountByNoteId(rawNote.id),
      collectStore.fetchCollectionCountByNoteId(rawNote.id)
    ])

    rawNote.likes = likeCount
    rawNote.collects = collectCount
    await commentStore.fetchCommentCountByNoteId(rawNote.id)

    if (!isCurrentUser.value && authStore.isAuthenticated) {
      await checkFollowStatus()
    }
    await fetchComments()

  } catch (e) {
    console.error('获取笔记失败:', e)
  }
}

const handleLike = async (noteId) => {
  if (!authStore.isAuthenticated) {
    alert('请先登录再进行点赞操作')
    return
  }
  
  try {
    isLiking.value = true
    // 调用存储方法更新点赞状态
    await noteStore.toggleNoteLike(noteId)
  } catch (error) {
    console.error('点赞失败:', error)
    alert('操作失败，请稍后重试')
  } finally {
    isLiking.value = false
  }
}

const handleCollect = async (noteId) => {
  if (!authStore.isAuthenticated) {
    alert('请先登录再进行收藏操作')
    return
  }
  
  try {
    isCollecting.value = true
    // 调用存储方法更新收藏状态
    await noteStore.toggleNoteCollect(noteId)
  } catch (error) {
    console.error('收藏失败:', error)
    alert('操作失败，请稍后重试')
  } finally {
    isCollecting.value = false
  }
}

const handleFollow = async () => {
  if (!authStore.isAuthenticated) {
    alert('请先登录再进行关注操作')
    return
  }
  
  try {
    isFollowingLoading.value = true
    if (isFollowing.value) {
      await followStore.unfollowUser(note.value.user.id)
    } else {
      await followStore.followUser(note.value.user.id)
    }
    isFollowing.value = !isFollowing.value
  } catch (error) {
    console.error('关注操作失败:', error)
    alert('操作失败，请稍后重试')
  } finally {
    isFollowingLoading.value = false
  }
}

const checkFollowStatus = async () => {
  if (!authStore.isAuthenticated || !note.value?.user) return
  
  try {
    isFollowingLoading.value = true
    isFollowing.value = await followStore.checkIsFollowing(
      authStore.user.id, 
      note.value.user.id
    )
  } catch (error) {
    console.error('检查关注状态失败:', error)
  } finally {
    isFollowingLoading.value = false
  }
}

const fetchComments = async () => {
  if (!note.value) return
  try {
    // 获取评论树
    await commentStore.fetchCommentsTreeByNoteId(note.value.id)
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

const startReply = (commentId, username) => {
  replyingTo.value = commentId
  replyingToUsername.value = username
  focusCommentInput()
}

const cancelReply = () => {
  replyingTo.value = null
  replyingToUsername.value = ''
}

const submitComment = async () => {
  if (!commentText.value.trim()) return
  if (!authStore.isAuthenticated) {
    alert('请先登录再发表评论')
    return
  }
  
  try {
    isCommenting.value = true
    
    // 准备评论数据
    const commentData = {
      noteId: note.value.id,
      content: commentText.value,
      userId: authStore.user.id,
      parentId: replyingTo.value // 如果是回复，设置parentId
    }
    
    await commentStore.createComment(commentData)
    commentText.value = ''
    
    // 重置回复状态
    cancelReply()
    
    // 刷新评论列表
    await fetchComments()
    
    // 更新笔记对象中的评论数
    note.value.comments = commentCount.value
  } catch (error) {
    console.error('发表评论失败:', error)
    alert('发表评论失败，请稍后重试')
  } finally {
    isCommenting.value = false
  }
}

const focusCommentInput = () => {
  commentInput.value?.focus()
}

const handleAvatarError = (e) => {
  e.target.src = 'https://picsum.photos/id/64/100/100'
}

const handleCoverImageError = (e) => {
  e.target.src = 'https://picsum.photos/id/1/800/400'
}

const handleCommentAvatarError = (e) => {
  e.target.src = 'https://picsum.photos/id/64/40/40'
}

const closeModal = () => {
  emit('close')
}

// 生命周期
onMounted(fetchNote)

// 监听笔记ID变化
watch(() => props.noteId, (newVal) => {
  if (newVal) fetchNote()
})
</script>

<style scoped>
/* 新增样式 */
.reply-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 8px;
  margin-top: 8px;
}

.reply-btn:hover {
  color: var(--color-primary);
}

.replying-to {
  background-color: #f0f0f0;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cancel-reply {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 12px;
}

.cancel-reply:hover {
  color: #ff4444;
}

/* 保持原有样式不变 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  position: relative;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  overflow-y: auto;
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
}

.icon {
  width: 24px;
  height: 24px;
  color: #666;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 120, 255, 0.1);
  border-radius: 50%;
  border-top-color: var(--color-primary);
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-state {
  text-align: center;
  padding: 40px 20px;
}

.error-message {
  color: #ff4444;
  font-size: 14px;
  margin: 8px 0;
}

.retry-btn {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  margin-top: 12px;
  cursor: pointer;
}

.note-content {
  padding: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: bold;
  margin-bottom: 4px;
}

.post-time {
  font-size: 12px;
  color: #888;
}

.follow-btn {
  padding: 6px 16px;
  background-color: var(--color-primary);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.follow-btn:hover {
  background-color: #3d43b1;
}

.follow-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.cover-image {
  width: 100%;
  max-height: 300px;
  object-fit: contain;
  border-radius: 8px;
  margin-bottom: 16px;
}

.note-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 12px;
}

.note-text {
  line-height: 1.6;
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  justify-content: space-around;
  padding: 12px 0;
  border-top: 1px solid #eee;
  margin-top: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.action-btn.active {
  color: var(--color-primary);
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-icon {
  width: 20px;
  height: 20px;
}

.comment-input-container {
  display: flex;
  flex-direction: column;
  margin-top: 16px;
  border-top: 1px solid #eee;
  padding-top: 16px;
}

.comment-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  font-size: 14px;
}

.send-btn {
  margin-left: 12px;
  padding: 8px 16px;
  background-color: var(--color-primary);
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 14px;
  cursor: pointer;
}

.send-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.comments-section {
  margin-top: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
}

.loading-comments {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.small-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(0, 194, 255, 0.3);
  border-radius: 50%;
  border-top-color: var(--color-primary);
  animation: spin 1s linear infinite;
}

.no-comments {
  text-align: center;
  padding: 24px 0;
  color: #888;
}

.comments-list {
  margin-top: 12px;
}

.comment-item {
  display: flex;
  margin-bottom: 16px;
}

.comment-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.comment-user {
  font-weight: bold;
  margin-right: 8px;
}

.comment-time {
  font-size: 12px;
  color: #888;
}

.comment-text {
  line-height: 1.5;
  margin-bottom: 8px;
}

/* 回复样式 */
.replies {
  margin-top: 12px;
  padding-left: 24px;
  border-left: 2px solid #eee;
}

.reply-item {
  display: flex;
  margin-bottom: 12px;
}

.reply-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.reply-content {
  flex: 1;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.reply-user {
  font-weight: bold;
  margin-right: 8px;
  font-size: 14px;
}

.reply-time {
  font-size: 11px;
  color: #888;
}

.reply-text {
  font-size: 14px;
  line-height: 1.4;
}
</style>